package handlers

import (
	"net/http"
	"strconv"

	alertv1 "github.com/devops-smartbot/devops-smartbot/proto/gen/go/alert/v1"
	commonv1 "github.com/devops-smartbot/devops-smartbot/proto/gen/go/common/v1"
	"github.com/devops-smartbot/devops-smartbot/services/api-gateway/internal/clients"
	"github.com/gin-gonic/gin"
)

type AlertHandler struct {
	alertClient clients.AlertClient
}

func NewAlertHandler(alertClient clients.AlertClient) *AlertHandler {
	return &AlertHandler{alertClient: alertClient}
}

// ListAlerts handles GET /api/alerts
func (h *AlertHandler) ListAlerts(c *gin.Context) {
	page, _ := strconv.ParseInt(c.DefaultQuery("page", "1"), 10, 32)
	pageSize, _ := strconv.ParseInt(c.DefaultQuery("pageSize", "20"), 10, 32)

	req := &alertv1.ListAlertsRequest{
		Pagination: &commonv1.Pagination{
			Page:     int32(page),
			PageSize: int32(pageSize),
		},
	}

	// Add filters if provided
	if severity := c.QueryArray("severity"); len(severity) > 0 {
		req.Severity = severity
	}
	if status := c.QueryArray("status"); len(status) > 0 {
		req.Status = status
	}

	resp, err := h.alertClient.ListAlerts(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// Transform alerts to add alertname field for frontend compatibility
	alerts := make([]map[string]interface{}, 0, len(resp.Alerts))
	for _, alert := range resp.Alerts {
		alertMap := map[string]interface{}{
			"id":             alert.Id,
			"fingerprint":    alert.Fingerprint,
			"name":           alert.Name,
			"alertname":      alert.Name, // Add alertname for frontend compatibility
			"severity":       alert.Severity,
			"status":         alert.Status,
			"instance":       alert.Instance,
			"description":    alert.Description,
			"startsAt":       alert.StartsAtUnix,  // For frontend compatibility
			"starts_at_unix": alert.StartsAtUnix,
			"endsAt":         alert.EndsAtUnix,    // For frontend compatibility
			"ends_at_unix":   alert.EndsAtUnix,
			"labels":         alert.Labels,
			"annotations":    alert.Annotations,
		}
		alerts = append(alerts, alertMap)
	}

	c.JSON(http.StatusOK, gin.H{
		"data": alerts,
		"pagination": gin.H{
			"total":    resp.Total,
			"page":     page,
			"pageSize": pageSize,
		},
	})
}

// GetAlert handles GET /api/alerts/:id
func (h *AlertHandler) GetAlert(c *gin.Context) {
	id := c.Param("id")

	resp, err := h.alertClient.GetAlert(c.Request.Context(), &alertv1.GetAlertRequest{
		Id: id,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Alert not found"})
		return
	}

	// Transform to match frontend expectations
	alertData := map[string]interface{}{
		"id":             resp.Id,
		"fingerprint":    resp.Fingerprint,
		"name":           resp.Name,
		"alertname":      resp.Name, // For frontend compatibility
		"severity":       resp.Severity,
		"status":         resp.Status,
		"instance":       resp.Instance,
		"description":    resp.Description,
		"startsAt":       resp.StartsAtUnix,  // For frontend compatibility
		"starts_at_unix": resp.StartsAtUnix,
		"endsAt":         resp.EndsAtUnix,    // For frontend compatibility
		"ends_at_unix":   resp.EndsAtUnix,
		"labels":         resp.Labels,
		"annotations":    resp.Annotations,
	}

	c.JSON(http.StatusOK, gin.H{"data": alertData})
}

// GetAlertStatistics handles GET /api/alerts/statistics
func (h *AlertHandler) GetAlertStatistics(c *gin.Context) {
	// Get all alerts to calculate statistics
	req := &alertv1.ListAlertsRequest{
		Pagination: &commonv1.Pagination{
			Page:     1,
			PageSize: 10000, // Get all alerts
		},
	}

	resp, err := h.alertClient.ListAlerts(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// Calculate statistics
	var active, resolved, critical, total int64
	total = int64(resp.Total)

	for _, alert := range resp.Alerts {
		if alert.Status == "active" || alert.Status == "firing" {
			active++
		} else if alert.Status == "resolved" {
			resolved++
		}

		if alert.Severity == "critical" {
			critical++
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"active":   active,
			"resolved": resolved,
			"critical": critical,
			"total":    total,
		},
	})
}
